var tian_di_tu_satellite_layer = new ol.layer.Tile({
    title: "天地图底图",
    // visible:false,
    source: new ol.source.XYZ({
        url: 'http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=1b261919df4cdb8ef96ad2a1604d0d72'
    })
});
var tian_di_tu_annotation = new ol.layer.Tile({
    title: "天地图文字标注",
    source: new ol.source.XYZ({
        url: 'http://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=1b261919df4cdb8ef96ad2a1604d0d72'
    })
});
var map = new ol.Map({
    target: 'map',
    layers: [tian_di_tu_satellite_layer, tian_di_tu_annotation],
    overlays: [],
    view: new ol.View({
        center: [68.554, 26.6738],
        projection: 'EPSG:4326',
        zoom: 3.5
    }),
    //比例尺
});
//图层管理控件
var layerSwitcher = new ol.control.LayerSwitcher({
    className: "layerControl"
});
map.addControl(layerSwitcher);
//添加拾取坐标控件
map.addControl(new ol.control.MousePosition({
    className: "label-mousePosition"
}));
map.addControl(new ol.control.ZoomSlider());
map.addControl(new ol.control.ZoomToExtent());
map.addControl(new ol.control.ScaleLine());
map.addControl(new ol.control.FullScreen());
var dataArray = {
    seaSilk: {
        url: 'data/seaSilk.json',
        name: '丝绸之路海陆',
        id: 'seaSilk',
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#1c4587',
                width: 5,
                lineCap: 'round'
            })
        })
    },
    landSilk: {
        url: 'data/landSilk.json',
        name: '丝绸之路陆路',
        id: 'landSilk',
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#cc4125',
                width: 5,
                lineCap: 'round'
            })
        })
    },
    aicientSilk: {
        url: 'data/aicientSilk.json',
        name: '古代丝绸之路',
        id: 'aicientSilk',
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#ffaa00',
                width: 5,
                lineCap: 'round'
            })
        })
    },
    ruinsRoadSilk: {
        url: 'data/ruinsRoadSilk.json',
        name: '申遗丝绸之路',
        id: 'ruinsRoadSilk',
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#274e13',
                width: 5,
                lineCap: 'round'
            })
        })
    },
    citySilk: {
        url: 'data/citySilk.json',
        name: '沿途城镇',
        id: 'citySilk',
        style: new ol.style.Style({
            image: new ol.style.Icon({
                src: './img/icon/city.png',
                size: [32, 32]
            })
        })
    },
    ruinsSilk: {
        url: 'data/ruinsSilk.json',
        name: '文化遗址',
        id: 'ruinsSilk',
        style: new ol.style.Style({
            image: new ol.style.Icon({
                src: './img/icon/ruins.png',
                size: [24, 24]
            })
        })
    },
}
var pointData = {};
for (let item in dataArray) {
    $.ajax({
        url: dataArray[item].url,
        type: "GET",//请求方式为get
        dataType: "json", //返回数据格式为json
        async: false,//设置ajax为同步请求, 默认为异步
        success: function (data) {
            if (dataArray[item].id == 'citySilk' || dataArray[item].id == 'ruinsSilk') {
                pointData[dataArray[item].id] = data.data;
                var source = new ol.source.Vector();
                for (var i = 0; i < data.data.length; i++) {
                    var feature = new ol.Feature({
                        geometry: new ol.geom.Point([data.data[i].lng, data.data[i].lat]),
                        att: data.data[i]
                    });
                    source.addFeature(feature);
                }
                var layer = new ol.layer.Vector({
                    title: dataArray[item].name,
                    source: source,
                    style: dataArray[item].style
                });
                map.addLayer(layer);

            } else {
                var vectorSource = new ol.source.Vector({
                    features: (new ol.format.GeoJSON()).readFeatures(data.line)
                });
                var layer = new ol.layer.Vector({
                    title: dataArray[item].name,
                    source: vectorSource,
                    style: dataArray[item].style
                });
                map.addLayer(layer);
            }

        }
    });
}

//创建popup
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var popupPosition = [];
/**
        * 在地图容器中创建一个Overlay
        */
var popup = new ol.Overlay({
    element: container,
    autoPan: true,
    positioning: 'bottom-center',
    stopEvent: false,
    autoPanAnimation: {
        duration: 250
    }
});
//添加关闭按钮的单击事件（隐藏popup）
closer.onclick = function () {
    popup.setPosition(undefined);  //未定义popup位置
    closer.blur(); //失去焦点
    popupPosition = [];
    return false;
};


function addFeatrueInfo(info) {
    //新增a元素
    var elementA = document.createElement('a');
    elementA.className = "markerInfo";
    elementA.tag = info.att.lng + '-' + info.att.lat;
    elementA.href = '#';
    elementA.onclick = function () {
        //定位
        map.getView().setCenter([info.att.lng, info.att.lat]);
        map.getView().setZoom(11);
    }
    popupPosition = [info.att.lng, info.att.lat];
    //elementA.innerText = info.att.title;
    setInnerText(elementA, info.att.country + '-' + info.att.name);
    content.appendChild(elementA); // 新建的div元素添加a子节点
    //新增div元素
    var elementDiv = document.createElement('div');
    elementDiv.className = "markerText";
    //elementDiv.innerText = info.att.text;
    setInnerText(elementDiv, info.att.description);
    content.appendChild(elementDiv); // 为content添加div子节点
    //新增img元素
    //https://image.baidu.com/search/index?tn=baiduimage&word='+info.att.name+'
    var elementA2 = document.createElement('a');
    elementA2.className = "markerInfo";
    elementA2.tag = info.att.lng + '-' + info.att.lat;
    elementA2.href = '#';
    elementA2.onclick = function () {
        //搜索百度图片展示
        window.open('https://image.baidu.com/search/index?tn=baiduimage&word=' + info.att.name);
    }
    setInnerText(elementA2, '查看图片');
    content.appendChild(elementA2); // 新建的div元素添加a子节点
    // var elementImg = document.createElement('img');
    // elementImg.className = "markerImg";
    // elementImg.src = info.att.imgname;
    // content.appendChild(elementImg); // 为content添加img子节点          
}
function setInnerText(element, text) {
    if (typeof element.textContent == "string") {
        element.textContent = text;
    } else {
        element.innerText = text;
    }
}
map.on('click', function (e) {
    //在点击时获取像素区域
    var pixel = map.getEventPixel(e.originalEvent);
    map.forEachFeatureAtPixel(pixel, function (feature) {
        //coodinate存放了点击时的坐标信息
        var coodinate = e.coordinate;
        console.log(feature);
        //设置弹出框内容，可以HTML自定义
        content.innerHTML = '';
        if (feature.N.att) {
            addFeatrueInfo(feature.N); //在popup中加载当前要素的具体信息
            //设置overlay的显示位置
            popup.setPosition(coodinate);
            //显示overlay
            map.addOverlay(popup);
        }

    });
});
map.on("moveend", function (e) {
    var zoom = map.getView().getZoom();  //获取当前地图的缩放级别
    if (popup.getPosition() != undefined) {
        console.log(popupPosition);
        popup.setPosition(popupPosition)
    }


    //popup.setPosition()

});
/*为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态*/
map.on('pointermove', function (e) {
    var pixel = map.getEventPixel(e.originalEvent);
    var hit = map.hasFeatureAtPixel(pixel);
    map.getTargetElement().style.cursor = hit ? 'pointer' : '';
})
//恢复初始位置
$('.location-reset').click(function () {
    map.getView().setCenter([68.554, 26.6738]);
    map.getView().setZoom(3.5);
})

layui.use('layer', function () {
    var $ = layui.jquery, layer = layui.layer, table = layui.table;
    $('.citySilk').click(function () {
        if (pointData.citySilk) {
            layer.open({
                type: 2
                ,title:""
                , offset: 'rb' //具体配置参考：http://doc/modules/layer.html#offset
                , id: 'layerDemo' //防止重复弹出
                , content: '../page/table.html'
                ,area: ['823px', '300px']
                , btnAlign: 'c' //按钮居中
                , shade: 0 //不显示遮罩
                , yes: function () {
                    layer.closeAll();
                }
            });
        }
    })
    $('.ruinsSilk').click(function () {
        if (pointData.citySilk) {
            layer.open({
                type: 2
                ,title:""
                , offset: 'rb' //具体配置参考：http://doc/modules/layer.html#offset
                , id: 'layerDemo' //防止重复弹出
                , content: '../page/table2.html'
                ,area: ['823px', '300px']
                , btnAlign: 'c' //按钮居中
                , shade: 0 //不显示遮罩
                , yes: function () {
                    layer.closeAll();
                }
            });
        }
    })
});